# -*- coding: UTF-8 -*-
"""
@Time : 2022/10/24 14:20 
@Author : Gloria
@Site : 
"""
import time

from django.core.handlers.wsgi import WSGIRequest
from django.db.models import F
from django.db.models.query import QuerySet

from django.http import JsonResponse
from django.shortcuts import redirect
from django.views import View
from api.views.login import clean_form
from app01.models import Avatars, UserInfo, Feedback, UserTags, Articles
import time
from api.forms.user_from import *




# 修改密码
class EditPasswordView(View):
    def post(self, request):
        res = {
            "msg": '密码修改成功！',
            'self': None,
            'code': 414,
        }
        data = request.data
        form = EditPasswordForm(data, request=request)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)
        user = request.user
        user.set_password(data['pwd'])
        user.save()
        auth.logout(request)  # 退出登录
        res['code'] = 0
        return JsonResponse(res)


# 选择头像
class EditAvatarView(View):
    def put(self, request):
        res = {
            'msg': '头像修改成功',
            'code': 414,
        }
        avatar_id = request.data.get('avatar_id')

        # 要判断用户的登录状态
        user = request.user
        sign_status = user.sign_status
        avatar = Avatars.objects.get(nid=avatar_id)

        if sign_status == 0:
            # 用户名密码注册  账号正常
            user.avatar_id = avatar_id
            avatar_url = avatar.url.url
            user.avatar_url = avatar_url
        elif sign_status == 1:
            res['msg'] = '账号异常, 请联系管理员'
        elif sign_status == 2:
            res['msg'] = '账号被封禁请联系管理员'

        user.save()
        res['data'] = avatar.url.url
        res['code'] = 0
        return JsonResponse(res)


# 添加标签
def add_user_tags(tags, user_obj):
    for tag in tags:
        if tag.isdigit():
            user_obj.tag.add(tag)
        else:
            # 先创建，再多对多关联
            tag_obj = UserTags.objects.create(title=tag)
            user_obj.tag.add(tag_obj.nid)


class UserInformationView(View):
    def post(self, request):
        res = {
            'msg': '简介，标签信息绑定成功！',
            'code': 444,
            'data': None
        }

        data = request.data
        # print(data)
        # 如果没有重写form,就不传request，要传request一定要重写
        form = UserInformationForm(data, request=request)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # user_obj = UserInfo.objects.create(**form.cleaned_data)
        # user_obj = UserInfo.objects.get_or_create(**form.cleaned_data)
        # tags = data.get('tags')

        id = request.user.nid
        user_obj = UserInfo.objects.filter(nid=id)
        user_obj.update(**form.cleaned_data)

        tags = data.get('tags')
        obj: UserInfo = user_obj.first()

        add_user_tags(tags, obj)
        # add_user_tags(tags, user_obj)

        res['code'] = 0
        # res['data'] = user_obj.nid
        return JsonResponse(res)

    def put(self, request, nid):
        res = {
            'msg': '简介，标签信息编辑成功！',
            'code': 444,
            'data': None
        }

        data = request.data

        form = UserInformationForm(data, request=request)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # 编辑
        user_query = UserInfo.objects.filter(nid=nid)
        user_query.update(**form.cleaned_data)

        tags = data.get('tags')
        obj: UserInfo = user_query.first()
        # 先清空再添加
        obj.tag.clear()
        # if tags:
        #     obj.tag.add(*tags)

        add_user_tags(tags, obj)

        res['code'] = 0
        return JsonResponse(res)


# 信息绑定
class EditUserInfoView(View):
    def put(self, request):
        res = {
            'code': 332,
            'msg': '信息绑定成功！',
            "self": None,
        }

        # 校验时间
        valid_email_obj = request.session.get('valid_email_obj')
        if not valid_email_obj:
            res['msg'] = '请先获取验证码！'
            return JsonResponse(res)
        time_stamp = valid_email_obj['time_stamp']
        now_stamp = time.time()
        # 五分钟超时
        if (now_stamp - time_stamp) > 300:
            res['msg'] = '验证码超时，请重新获取！'
            return JsonResponse(res)

        form = EditUserInfoForm(request.data, request=request)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # 绑定信息
        user = request.user
        user.email = form.cleaned_data['email']
        user.save()

        res['code'] = 0
        return JsonResponse(res)


# 取消收藏
class CancelCollection(View):
    def post(self, request):
        nid_list = request.POST.getlist('nid')
        request.user.collects.remove(*nid_list)
        # 这里有个bug，取消收藏，对应文章的收藏数也要-1
        article_query: QuerySet = Articles.objects.filter(nid__in=nid_list)
        article_query.update(collects_count=F('collects_count') - 1)
        return redirect('/backend/')


# 意见反馈
class FeedBackView(View):
    def post(self, request):
        res = {
            'msg': '反馈成功，道元仪正在给你回信！',
            "code": 543,
            'self': None
        }
        form = FeedBackForm(request.data)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)
        Feedback.objects.create(**form.cleaned_data)
        res['code'] = 0
        return JsonResponse(res)
